package com.xqboss.apps.service.box;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xqboss.apps.domain.box.Box;
import com.xqboss.apps.domain.box.BoxSimulatedRecord;
import com.xqboss.apps.mapper.box.BoxSimulatedRecordMapper;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.exception.ServiceException;
import com.xqboss.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Administrator
 */
@Service
public class BoxSimulatedRecordService extends ServiceImpl<BoxSimulatedRecordMapper, BoxSimulatedRecord> {

    @Autowired
    private BoxService boxService;

    /**
     * 增发虚拟销量
     *
     * @param boxId
     * @param simulatedSales
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public R simulatedAdd(Long boxId, Integer simulatedSales) {
        if (simulatedSales <= 0) {
            return R.fail("虚拟销量必须大于零");
        }
        Box box = boxService.getById(boxId);
        if (ObjUtil.isNull(box)) {
            return R.fail("箱子不存在");
        }
        if (simulatedSales > box.getStock()) {
            return R.fail("虚拟销量超过库存数");
        }
        //新增虚拟销量
        boolean update = boxService.update(new LambdaUpdateWrapper<Box>()
                .setSql("simulated_sales=simulated_sales+" + simulatedSales)
                .eq(Box::getId, boxId)
        );
        if (!update) {
            throw new ServiceException("修改虚拟销量失败");
        }
        boxService.takeStock(box.getId(), simulatedSales);
        BoxSimulatedRecord record = new BoxSimulatedRecord();
        record.setAmount(simulatedSales);
        record.setBoxId(box.getId());
        record.setUserId(SecurityUtils.getUserId());
        record.setUserName(SecurityUtils.getUsername());
        //添加虚拟销量记录
        boolean b = save(record);
        if (!b) {
            throw new ServiceException("添加虚拟销量失败");
        }
        return R.ok();
    }
}
